<template>
  <div>
<van-cell @click="onSearch(item)" v-for="(item,index) in suggestions" :key="index" icon="search">
  <template #title>
    <div v-html="highText(item)"></div>
  </template>
</van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  props: {
    valueText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  beforeDestroy () {
    clearTimeout(this.setid)
  },
  watch: {
    valueText: {
      immediate: true,
      handler (newVal) {
        clearTimeout(this.setid)
        this.setid = setTimeout(async () => {
          const res = await getSearchSuggestion(newVal)
          this.suggestions = res.options
        }, 700)
      }
    }
  },
  created () {

  },

  methods: {
    highText (item) {
      const replaceText = '<span style="color:red">' + this.valueText + '</span>'
      const reg = new RegExp(this.valueText, 'gi')
      return item.replace(reg, replaceText)
    },
    onSearch (item) {
      this.$emit('onSearch', item)
    }
  }
}
</script>

<style scoped lang='less'>

</style>
